package com.bosssoft.trainee.gateway.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: wuxin
 * @Project: rbac-SpringCloud
 * @Date: 2022/7/15
 * @Description:
 */
@Slf4j
@Component
public class MySecurityContextRepository implements ServerSecurityContextRepository {
    @Autowired
    MyAuthenticationManager myAuthenticationManager;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Override
    public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
        return Mono.empty();
    }

    @Override
    public Mono<SecurityContext> load(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst(tokenHeader);
        log.info("MySecurityContextRepository authorization = {}", token);

        return myAuthenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(token, null))
                .map(SecurityContextImpl::new);
    }
}
